package cn.edu.service.impl;

import cn.edu.mapper.StockMapper;
import cn.edu.pojo.Stock;
import cn.edu.service.StockServiceLock;
import cn.edu.service.StockServiceRedis;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author Mr.ma
 * @since 2022/12/8 16:09
 **/
@Service
public class StockServiceRedisImpl implements StockServiceRedis {
    @Resource
    private StockMapper stockMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public String decrement(Integer id) {
        ValueOperations<String, String> forValue = stringRedisTemplate.opsForValue();
        Boolean flag = forValue.setIfAbsent("stock::" + id, "ma", 30, TimeUnit.SECONDS);
        if (flag) {
            try {
                Stock stock = stockMapper.selectById(id);
                if (stock != null) {
                    if (stock.getStock() > 0) {
                        stock.setStock(stock.getStock() - 1);
                        stockMapper.updateById(stock);
                        System.out.println("修改库存数量成功，剩余库存为：" + stock.getStock());
                        return "修改库存数量成功，编号为" + id + "的商品剩余库存为：" + stock.getStock();
                    }
                }
                System.out.println("编号为" + id + "的商品剩余库存不足");
                return "编号为" + id + "的商品剩余库存不足";
            }finally {
                stringRedisTemplate.delete("stock::" + id);
            }
        } else {
            System.out.println("系统正在维护，请稍后再试");
            return "系统正在维护，请稍后再试";
        }
    }
}
